package evolution.visualization;

import javax.swing.JDialog;
import javax.swing.SwingUtilities;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.xy.XYDataset;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;

import evolution.gui.CoevolutionGUI;
import evolution.individual.Individual;

public class CoevolutionChart {

	public static void createConvergenceChart(final String title,
			Individual[][] populations) {
		final XYSeriesCollection dataset = new XYSeriesCollection();

		int iterations = populations.length;
		XYSeries[] series = new XYSeries[populations[0].length];

		for (int i = 0; i < iterations; i++) {
			Individual[] population = populations[i];

			for (int j = 0; j < population.length; j++) {
				if (series[j] == null) {
					series[j] = new XYSeries("Populacja " + j);
				}
				double fitness = population[j].getFitness();
				double val = population[j].getFitnessFunction()
						.convertToRealValue(fitness);
				series[j].add(i, val);
			}

		}
		for (int i = 0; i < series.length; i++) {
			dataset.addSeries(series[i]);
		}

		JFreeChart chart = createChart(title, dataset);
		final ChartPanel chartPanel = new ChartPanel(chart);

		SwingUtilities.invokeLater(new Runnable() {

			@Override
			public void run() {
				JDialog chartDialog = new JDialog(CoevolutionGUI.getInstance(),
						title, false);
				chartDialog.setLocationByPlatform(true);
				chartDialog.getContentPane().add(chartPanel);
				chartDialog.pack();
				chartDialog.setVisible(true);
			}
		});
	}

	/**
	 * Creates a sample chart.
	 * 
	 * @param dataset
	 *            the dataset.
	 * 
	 * @return A sample chart.
	 */
	private static JFreeChart createChart(String title, XYDataset dataset) {
		JFreeChart chart = ChartFactory.createXYLineChart(title,
				"Iteracja (epoka)", "Wartość funkcji celu", dataset,
				PlotOrientation.VERTICAL, true, true, false);
		return chart;
	}

}
